<template>
<div>
	<!--文件预览-->
	<el-dialog title='文件操作' :visible.sync="fileOptVisible" :fullscreen="fullscreen">
		<div slot="title">
	    <span class="title-text">{{file.name}}</span>
	    <el-button type="text" size="mini"><i class="fa fa-download"></i> <a :href="file.url" download>下载</a></el-button>
	    <button type="button" class="el-fullscreen" @click="fullScreen"><i :class="screenIcon"></i></button>
	  </div>
	  <div class="pdfTitle" v-if="previewType=='pdf'">
	    <el-button size="small" @click="changePdfPage(0)">上一页</el-button>
	    <span>{{currentPage}}/{{pageCount}}</span>
	    <el-button size="small" @click="changePdfPage(1)">下一页</el-button>
			<pdf
				:src="file.url"
				:page="currentPage"
				@num-pages="pageCount=$event"
				@page-loaded="currentPage=$event">
			</pdf>
		</div>

		<el-image
			v-if="previewType=='image'"
			style="width: 100%;"
    	:src="file.url">
  	</el-image>
	</el-dialog>

	<!--上传dialog-->
	<el-dialog title="上传附件" :visible.sync="uploadVisible" :fullscreen="fullscreen">
		<div slot="title">
	    <span class="title-text">上传附件</span>
	    <button type="button" class="el-fullscreen" @click="fullScreen"><i :class="screenIcon"></i></button>
	  </div>
		<Upload :fields="fields" :instance="currProID" @getProjects="getProjects"></Upload>
	</el-dialog>

	<!--添加/编辑 dialog-->
	<el-dialog :title="action+'人员'" :visible.sync="proVisible" center width="40%">
		<el-form :model="form" :rules="rules">
	    <el-form-item :label="field.ch_name" label-width="80px" :prop="field.en_name" v-for="(field,index) in fields1" :key="index">
	      <el-date-picker
		      type="datetime"
		      placeholder="选择日期"
		      v-if="field.type_name=='日期'"
		      v-model="form[field.en_name]">
		    </el-date-picker>
		    <el-select v-model="form[field.en_name]" placeholder="请选择" v-else-if="field.type_name=='枚举'">
		    	<el-option
		    		size="mini"
			      v-for="item in field.field_type"
			      :key="item.key"
			      :label="item.value"
			      :value="item.value">
			    </el-option>
		    </el-select>
		    <el-input v-model="form[field.en_name]" v-else></el-input>
	    </el-form-item>
	  </el-form>
	  <div slot="footer" class="dialog-footer">
	    <el-button @click="proVisible = false">取 消</el-button>
	    <el-button type="primary" @click="save">确 定</el-button>
	  </div>
	</el-dialog>


	<el-row>
		<el-button type="text" @click="showSearch">高级搜索<i :class="downClass"></i></el-button>
		<el-button size="small" type="danger" style="float:right;" plain>批量删除</el-button>
		<el-button size="small" type="primary" style="float:right;" plain @click="add()">添加</el-button>
	</el-row>
	<el-row v-show="isSearch" style="padding:10px;">
		<el-col :lg="8" v-for="(field,index) in fields" :key="index" style="margin-bottom: 10px;">
			<div class="search-key">{{field.ch_name}}: </div>
			<el-date-picker
	      size="mini"
	      type="datetimerange"
	      range-separator="至"
	      start-placeholder="开始日期"
	      end-placeholder="结束日期"
	      v-if="field.type_name=='日期'"
	      v-model="searchData[field.en_name]">
	    </el-date-picker>
			<el-input v-else size="mini" v-model="searchData[field.en_name]" style="width: 400px;"></el-input>
		</el-col>
		<el-col style="text-align: right;">
			<el-button icon="el-icon-search" size="mini" type="primary" @click="search">搜索</el-button>
		</el-col>
		
	</el-row>
	<el-row style="margin-top: 20px;">
		<el-table
			:data="projects"
		  border
		  style="width: 100%"
		  :header-cell-style="{color:'#606266'}">
		  <el-table-column
	      type="selection"
	      width="55">
	    </el-table-column>
		  <el-table-column 
		  	v-for="(field,index) in fields"
		  	:label="field.ch_name"
		  	:key="index"
		  	:prop="field.en_name">
		  	<template slot-scope="scope">
		  		<span v-if="urlJudge(scope.row[field.en_name])">
		  			<div v-for="(item,index) in scope.row[field.en_name]" class="file-link">
		  				<span @click="fileOpt(item)" style="cursor: pointer;">{{item.name}}</span>
		  			</div>
		  		</span>
        	<span v-else>{{scope.row[field.en_name]}}</span>
        </template>
		  </el-table-column>
		  
		  <el-table-column
		  	fixed="right"
		    label="操作"
		    width="180">
		    <template slot-scope="scope">
	    		<el-button size="mini" @click="edit(scope)" icon="el-icon-edit" type="primary" title="编辑"></el-button>
	      	<el-button size="mini" @click="beforeDel(scope)"  icon="el-icon-delete" type="danger" title="删除"></el-button>
	      	<el-button size="mini" @click="upload(scope)" icon="el-icon-upload" type="success" title="上传附件"></el-button>
		    </template>
		  </el-table-column>
		</el-table>
	</el-row>
</div>
</template>
<script>
import {getAPItokenRes,postAPItoken,putAPItoken,deleteAPItoken} from '@/utils/api'
import Upload from './upload'
import pdf from 'vue-pdf'
export default {
	components: {
		Upload,
		pdf
	},
	data () {
		return {
			previewType: null,
			currentPage: 1, // pdf文件页码
      pageCount: 0, // pdf文件总页数
			file: {},
			fullscreen: false,
			screenIcon: 'fa fa-expand',
			action: '添加',
			form: {},
			fileOptVisible:  false,
			uploadVisible: false,
			proVisible: false,
			tempName: {},
			fields: [],
			fields1: [],
			projects: [],
			currProID: null,
			isSearch: false,
			downClass: 'fa fa-angle-double-up',
			searchData: {},
			rules: {},
			currTempID: this.$route.query.id
		}
	},
	methods: {
		showSearch () {
			if (this.isSearch) {
				this.downClass = 'fa fa-angle-double-up'
				this.isSearch = false
			} else {
				this.downClass = 'fa fa-angle-double-down'
				this.isSearch = true
			}
		},
		search () {
			const promise = postAPItoken(API.instSearch,{'search':this.searchData,'template':this.currTempID},this.token)
			promise.then((data)=>{
				this.projects = data
			})
		},
		getFields () {
			//每次需要把原先的数据清空, 不然会重复
      const promise = getAPItokenRes(API.tempField+'?display=1&template='+this.currTempID,this.token)
      promise.then((res)=>{
        if (res.status == 200) {
        	this.fields = res.data
        	this.fields.forEach((field)=>{
        		if (field.type_name != '文件' && field.type_name != '图片'){
        			this.fields1.push(field)
        		}
        		if(field.must){
        			this.rules[field.en_name] = [{required: true, message: '必填项', trigger: 'blur'}]
        		}
        	})
        	this.getProjects()
        }
      })
    },
    getProjects () {
      const promise = getAPItokenRes(API.instAPI+'?template='+this.currTempID,this.token)
      promise.then((res)=>{
        if (res.data.status) {
        	this.projects = res.data.data
        }
      })
    },
    save () {
    	this.form['template'] = this.currTempID
    	if (this.action == '添加') {
    		var promise = postAPItoken(API.instAPI,this.form,this.token)
    	} else {
    		var promise = putAPItoken(API.instAPI+this.form.id+'/',this.form,this.token)
    	}
    	promise.then((res)=>{
    		if(res.status){
    			this.$notify({
		        title: '成功',
		        message: '人员:'+this.form.name+', '+this.action+'成功',
		        type: 'success'
		      })
		      this.getProjects()
    		}
    		
    	})
    },
    add () {
    	this.action = '添加'
    	this.proVisible = true
    },
    edit (scope) {
    	this.action = '编辑'
    	this.form = scope.row
    	this.proVisible = true
    },
    upload (scope) {
    	this.currProID = scope.row.id
    	this.uploadVisible = true
    },
    detail (scope) {

    },
    beforeDel (scope) {
    	this.form = scope.row
    	this.$confirm('删除人员:'+this.form.name+', 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
      	this.executeDel()
        
      }).catch(() => {})
    },
    executeDel () {
    	const promise = deleteAPItoken(API.instAPI+this.form.id+'/',this.token)
    	promise.then((res)=>{
    		if (res.status == 204){
    			this.$notify({
	          type: 'success',
	          message: '删除成功!'
	        })
    		}
    		this.getProjects()
    	})
    },
    fullScreen () {
    	if (this.fullscreen){
				this.fullscreen = false
				this.screenIcon = 'fa fa-expand'
    	}else{
    		this.fullscreen = true
    		this.screenIcon = 'fa fa-compress'
    	}
    },
    urlJudge (field_val) {
    	if (field_val instanceof Array){
    		return true
    	}else{
    		return false
    	}
    },
    fileOpt (item) {
    	//this.file.src = pdf.createLoadingTask(item.url)
    	if (item.name.endsWith('pdf')){
    		this.previewType = 'pdf'
    	}else{
    		this.previewType = 'image'
    	}
    	this.file = item
    	this.fileOptVisible = true
    },
    changePdfPage (val) {
      // console.log(val)
      if (val === 0 && this.currentPage > 1) {
        this.currentPage--
        // console.log(this.currentPage)
      }
      if (val === 1 && this.currentPage < this.pageCount) {
        this.currentPage++
        // console.log(this.currentPage)
      }
    },
    detail (scope,member) {
    	this.$router.push({name: 'empDetail', query:{'id':1}})
    }
	},
	mounted () {
		this.token = this.$store.state.user.token
		this.getFields()
	},
	watch: { //通过watch来监听路由变化, 不同路由共用模版, 数据会不刷新
   "$route": function(){
   	this.currTempID = this.$route.query.id
   	this.projects = []
   	this.fields = []
		this.fields1 = []
    this.getFields()
   }
  }
}
</script>
<style scoped>
.search-key {
	color: #7a838f;
	font-size: 14px;
}
.el-button--mini, .el-button--mini.is-round {
  padding: 7px 7px;
}
.el-fullscreen {
  position: absolute;
  top: 20px;
  right: 40px;
  padding: 0;
  background: 0 0;
  border: none;
  outline: 0;
  cursor: pointer;
  font-size: 12px;
}
a {
	text-decoration:none;
	color: #409eff;
}

.file-link{
	overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>